package com.justgame.project.cloud.common.entity;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

@Slf4j
@Data
public class PageRequest<T> {
    private static final Integer DEFAULT_PAGE = 1;
    private static final Integer DEFAULT_SIZE = 10;

    private static final Integer MAX_SIZE = 1000;


    private Integer page;
    private Integer size;
    private String orderBy;
    private Long total;
    private List<T> rows;

    public PageRequest() {
        checkVal();
    }

    public PageRequest(int page, int size, String orderBy) {
        this.page = page;
        this.size = size;
        this.orderBy = orderBy;
        checkVal();
    }


    public PageRequest<T> BuildPageInfo(List<T> data) {
        PageInfo<T> pageInfo = new PageInfo<>(data);
        this.size = pageInfo.getSize();
        this.page = pageInfo.getPageNum();
        this.total = pageInfo.getTotal();
        this.rows = data;
        return this;
    }

    // 自定义分页查询，不走PageHelper
    public PageRequest<T> BuildPageInfo(List<T> data, Long totalCount) {
        this.total = totalCount;
        this.rows = data;
        return this;
    }

    public void startPage() {
        checkVal();
        if (StringUtils.isBlank(this.orderBy)) {
            PageHelper.startPage(this.page, this.size);
        } else {
            PageHelper.startPage(this.page, this.size, this.orderBy);
        }
    }

    private void checkVal() {
        if (this.page == null || this.page <= 0) this.page = DEFAULT_PAGE;
        if (this.size == null || this.size <= 0) this.size = MAX_SIZE;
    }

}
